package com.warwithinme.android.widgetwar;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

public class ButtonSync extends TButton
{
	private final static String INTENT_ACTION = "com.warwithinme.android.widgetwar.ButtonSync";
	public static final Uri CONTENT_URI = Uri.parse("content://sync/settings");
	public static final String SETTING_SYNC_PROVIDER_PREFIX = "sync_provider_";
	public static final String SETTING_LISTEN_FOR_TICKLES = "listen_for_tickles";
	private static final String[] PROJECTION = { "name", "value" };

	@Override
	public int canHandleIntent(Intent intent)
	{
		if(intent.getAction().equals(INTENT_ACTION))
			return ToggleWidget.HANDLING_TYPE_IMMEDIATE;
		else
			return ToggleWidget.HANDLING_TYPE_UNABLE;
	}

	@Override
	public int getButtonBmp(Context context)
	{
		boolean useBGData = getBoolean(context.getContentResolver(), SETTING_LISTEN_FOR_TICKLES, true);
		if(useBGData)
			return R.drawable.sync_on;
		else
			return R.drawable.sync_off;
	}

	@Override
	public String getIntentAction()
	{
		return INTENT_ACTION;
	}

	@Override
	public void toggleSetting(Context context)
	{
		ContentResolver cr = context.getContentResolver();
		boolean useBGData = getBoolean(cr, SETTING_LISTEN_FOR_TICKLES, true);
		putBoolean(cr, SETTING_LISTEN_FOR_TICKLES, !useBGData);
	}
	
	private void putBoolean(ContentResolver contentResolver, String name, boolean val) {
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("value", Boolean.toString(val));
        // this insert is translated into an update by the underlying Sync provider
        contentResolver.insert(CONTENT_URI, values);
    }

    private boolean getBoolean(ContentResolver contentResolver,String name, boolean def) {
        Cursor cursor = contentResolver.query(
        		CONTENT_URI,PROJECTION,
                "name=?",new String[] { name },
                null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                return Boolean.parseBoolean(cursor.getString(1));
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return def;
    }

}
